using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;

public class UiStatSlot : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    private Ui ui;
    [SerializeField] private StatType statType;
    private TextMeshProUGUI statNameText;
    private TextMeshProUGUI statValueText;
    private PlayerStats playerStats;
    [TextArea]
    [SerializeField] private string statDescription;

    private void Awake()
    {
        playerStats = FindAnyObjectByType<PlayerStats>();
        ui = FindAnyObjectByType<Ui>();
        statValueText = GetComponent<TextMeshProUGUI>();
        statNameText = transform.GetChild(0).GetComponentInChildren<TextMeshProUGUI>();
        SetStatName(statType.ToString());
        SetStatValue(playerStats.GetStat(statType).GetValue());
    }

    public void UpdateStatValueUi()
    {
        if (playerStats == null) return;
        SetStatValue(playerStats.GetStat(statType).GetValue());
        if (statType == StatType.Health)
        {
            statValueText.text = playerStats.GetMaxHp().ToString();
        }
        if (statType == StatType.Damage)
        {
            statValueText.text = playerStats.damage.GetValue().ToString();
        }
        if (statType == StatType.CritPower)
        {
            statValueText.text = (playerStats.critPower.GetValue() + playerStats.strength.GetValue()).ToString();
        }
        if (statType == StatType.CritChance)
        {
            statValueText.text = (playerStats.critChance.GetValue() + playerStats.agility.GetValue()).ToString();
        }
        if (statType == StatType.Evasion)
        {
            statValueText.text = (playerStats.evasion.GetValue() + playerStats.agility.GetValue()).ToString();
        }
        if (statType == StatType.MagicResistance)
        {
            statValueText.text = (playerStats.magicResistance.GetValue() + playerStats.intelligence.GetValue() * 3f).ToString();
        }
    }

    public void SetStatName(string name)
    {
        gameObject.name = $"stat - {name}";
        statNameText.gameObject.name = $"stat name - {name}";
        statNameText.text = name;
    }

    public void SetStatValue(string value)
    {
        statValueText.text = value;
    }

    public void SetStatValue(int value)
    {
        statValueText.text = value.ToString();
    }

    public void SetStatValue(float value)
    {
        statValueText.text = value.ToString("F2");
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        ui.StatTooltip.Show(statDescription);
    }
    
    public void OnPointerExit(PointerEventData eventData)
    {
        ui.StatTooltip.Hide();
    }
}
